package com.example.sixth.coree.controller;

import cn.hutool.core.util.RandomUtil;

import com.alibaba.fastjson.JSONObject;
import com.example.sixth.coree.entity.Messageinfo;
import com.example.sixth.coree.entity.Userinfo;
import com.example.sixth.coree.service.MessageinfoService;
import com.example.sixth.coree.service.RooominfoService;
import com.example.sixth.coree.service.UserinfoService;
import com.example.sixth.coree.utils.MiscUtil;

import com.example.sixth.coree.entity.ReturnData;


import com.example.sixth.coree.websocketservice.core;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * (Messageinfo)表控制层
 *
 * @author Zixiang Gao
 * @since 2021-06-23 18:15:15
 */
@RestController
@CrossOrigin
@RequestMapping("api/message")
public class MessageinfoController {
    /**
     * 服务对象
     */


    @Autowired
    private MessageinfoService service;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private RooominfoService rooominfoService;

    @RequestMapping("getMessageList")
    public ReturnData getMessageList(@RequestBody Map mp){
        return new ReturnData(200,"form cache",service.queryForList(mp.get("room_id").toString()));
    }

    @RequestMapping("send")
    public ReturnData send(@RequestBody Map mp){
        String access_token = (String) mp.get("access_token");
        Object at=mp.get("at");
        String msg = (String) mp.get("msg");
        String channel=(String) mp.get("where");
        String to= mp.get("to").toString();
        String type=mp.get("type").toString();
        if(MiscUtil.verifyToken(access_token)==null)
        return new ReturnData(401,"请登陆",null);
        JSONObject message;
        if (type.equals("img")) {
            message = messageimgbuilder(msg, userinfoService.queryById(Integer.parseInt(MiscUtil.verifyToken(access_token))));
        } else {
            message = messagetextbuilder(msg, userinfoService.queryById(Integer.parseInt(MiscUtil.verifyToken(access_token))),at);
        }
        savemessage(message.get("message_id").toString(),MiscUtil.verifyToken(access_token),"text","channel",to,message.toString(),0,System.currentTimeMillis()/1000,System.currentTimeMillis()/1000);
        SendForALL(to,message.toString());
        return new ReturnData(200,"",null);
    }
    JSONObject messageimgbuilder(String imgurl, Userinfo userinfo){
        JSONObject res = new JSONObject();
        res.put("type","img");
        res.put("content",imgurl);
        res.put("resource",imgurl);
        res.put("at",false);
        res.put("message_time",System.currentTimeMillis()/1000);
        res.put("where","channel");
        res.put("message_id", RandomUtil.randomInt(50000000,99999999));
        res.put("user",userinfo);

        return res;
    }
    JSONObject messagetextbuilder(String text, Userinfo userinfo,Object at){

        JSONObject res = new JSONObject();
        res.put("type","text");
        res.put("content",text);
        res.put("resource",text);
        if(at.toString().equals("false"))
        res.put("at",false);
        else res.put("at",at);
        res.put("message_time",System.currentTimeMillis()/1000);
        res.put("where","channel");
        res.put("message_id", RandomUtil.randomInt(10000000,50000000));
        res.put("user",userinfo);

        return res;
    }

    public boolean savemessage(String messageid,String message_user,String message_type,String message_where,String message_to,String message_content,int message_status,long message_createtime,long message_updatetime){

        Messageinfo messageinfo = new Messageinfo();
        messageinfo.setMessage_id(messageid);
        messageinfo.setMessage_user(Integer.parseInt(message_user));
        messageinfo.setMessage_type(message_type);
        messageinfo.setMessage_where(message_where);
        messageinfo.setMessage_to(Integer.parseInt(message_to));
        messageinfo.setMessage_content(message_content);
        messageinfo.setMessage_status(message_status);
        messageinfo.setMessage_createtime(message_createtime);
        messageinfo.setMessage_updatetime(message_updatetime);
        return service.insert(messageinfo);

    }
    public boolean delmessage(String messageid){
        return service.deleteById(messageid);
      }
    @RequestMapping("back")
    public ReturnData deletemessage(@RequestBody Map map){
        String message_id = map.get("message_id").toString();
        String access_token=map.get("access_token").toString();
        String s = MiscUtil.verifyToken(access_token);
        if(s==null||delmessage(message_id)==false){
            return new ReturnData(401,"失败",null);
        }
        JSONObject message = messagebackbuilder(message_id, userinfoService.queryById(Integer.parseInt(s)));
        SendForALL(map.get("room_id").toString(),message.toString());
        ReturnData returnData = new ReturnData(200, "撤回成功",null);
        return returnData;
    }
    JSONObject messagebackbuilder(String id,Userinfo userinfo){
        JSONObject res = new JSONObject();
        res.put("message_id",id);
        res.put("type","back");
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        res.put("time",format.format(new Date()));
        res.put("user",userinfo);


        return res;
    }
    @RequestMapping("touch")
    ReturnData touch(@RequestBody Map mp){
        String at = mp.get("at").toString();
        String room_id=mp.get("room_id").toString();
        String access_token=mp.get("access_token").toString();
        String s = MiscUtil.verifyToken(access_token);
        if(s==null){
            return new ReturnData(401,"拍不动",null);
        }
        String s1 = Paiyipaibuilder(userinfoService.queryById(Integer.parseInt(s)), userinfoService.queryById(Integer.parseInt(at))).toString();
        SendForALL(room_id,s1);
         return new ReturnData(200,"拍好了",null);
    }

    JSONObject Paiyipaibuilder(Userinfo from,Userinfo to){
        Map map=new HashMap();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        map.put("time",format.format(new Date()));
        map.put("type","touch");
        map.put("user",from);
        map.put("at",to);
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(map);
        return jsonObject;
    }

    boolean SendForALL(String room_id,String message){
        ConcurrentHashMap<String, Session> stringSessionConcurrentHashMap = core.CHATMAP.get(room_id);
        for(Session value : stringSessionConcurrentHashMap.values()){
            try {
                value.getBasicRemote().sendText(message);
            } catch (IOException e) {
               return false;
            }

        }
        return true;
    }
    @RequestMapping("clear")
    ReturnData clearALL(@RequestBody Map mp){
        Object access_token = mp.get("access_token");
        if(MiscUtil.verifyToken(access_token.toString())==null){
            return new ReturnData(403,"无权删除",null);
        }
        boolean flag = service.deleteByroomid(Integer.parseInt(mp.get("room_id").toString()));
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("type","clear");
        jsonObject.put("user",userinfoService.queryById(Integer.parseInt(MiscUtil.verifyToken(access_token.toString()))));
        SendForALL(mp.get("room_id").toString(),jsonObject.toJSONString());
        return new ReturnData(200,flag==false?"删除失败":"删除成功",null);
    }

}